const path = require("path");
const fs = require("fs");
// const path=require("path");
let ignore = require("./ignore.js");
let dir = fs.readdirSync("./").filter(item => {
    return item.indexOf(".") == -1 && ignore.indexOf(item) == -1;
});

// console.log(dir);

//列出子文件
let HTMLList = [];
for (let i = 0; i < dir.length; i++) {
    HTMLList[i] = {
        group: dir[i],
        list: fsearch("./" + dir[i], ".html")
    }
}
//提取title
for (let i = 0; i < HTMLList.length; i++) {
    for (let k = 0; k < HTMLList[i].list.length; k++) {
        let path = HTMLList[i].list[k];
        let title = fgetTitle(path);
        HTMLList[i].list[k] = {
            path: path,
            title: title
        }
    }
}
//展示列表
for (let i = 0; i < HTMLList.length; i++) {
    console.log(HTMLList[i].group);
    for (let k = 0; k < HTMLList[i].list.length; k++) {
        console.log("  ", HTMLList[i].list[k].path, "  ", HTMLList[i].list[k].title);
    }
}
//转换成html代码
let addition = fs.readFileSync("./addition.json");
addition = JSON.parse(addition);
HTMLList.push(addition);
let html = "";
for (let i = 0; i < HTMLList.length; i++) {
    html += "<div>\n"
    html += `<p>${HTMLList[i].group}</p>\n`
    for (let k = 0; k < HTMLList[i].list.length; k++) {
        html += `<a href="${HTMLList[i].list[k].path}">${HTMLList[i].list[k].title}</a>\n`
    }
    html += "</div>\n"
}
console.log(html);
//插入到导航页
let file = fs.readFileSync("./index.html").toString();
let start = file.indexOf("<body>") + 6;
let end = file.indexOf("</body>");
file = file.substring(0, start) + html + file.substring(end);
fs.writeFileSync("./index.html", file);
//提取html文件中的title函数
function fgetTitle(path) {
    let title = "";
    let file = fs.readFileSync(path).toString();
    let start = file.indexOf("<title>") + 7;
    let end = file.indexOf("</title>");
    title = file.substring(start, end);
    return title;
}
//搜素文件函数
function fsearch(path, key) {
    let list = [];
    let dir = [];
    let all = fs.readdirSync(path);
    for (let i = 0; i < all.length; i++) {
        if (all[i].indexOf(".") == -1) {
            dir.push(all[i]);
        }
        if (all[i].indexOf(key) != -1) {
            list.push(path + "/" + all[i]);
        }
    }
    for (let i = 0; i < dir.length; i++) {
        list = list.concat(fsearch(path + "/" + dir[i], ".html"))
    }
    return list;
}

module.exports = {};